/**
 iTextUploader
 (C) 2008 Asgl (myselftdev@gmail.com)
 
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; version 2
 of the License.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

/* Revision: $Id: UploadView.m 33 2008-10-20 19:06:55Z myselftdev $ */

#import "UploadView.h"

@implementation UploadView

- (id)initWithFrame:(CGRect)frame dataObject:(PreferencesData*)theDataObject
{
	if (self = [super initWithFrame:frame])
	{
		data = [theDataObject retain];
		
		self.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0];
		
		UIButton *uploadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
		uploadButton.contentMode = UIViewContentModeRedraw;
		uploadButton.frame = CGRectMake(90.0, 40.0, 140.0, 40.0);
		uploadButton.font = [UIFont boldSystemFontOfSize:22.0];
		[uploadButton setTitle:@"Upload" forState:UIControlStateNormal];
		[uploadButton addTarget:self action:@selector(uploadButtonClicked) forControlEvents:UIControlEventTouchUpInside];
		[self addSubview:uploadButton];
		
		webFrame = [ [UIWebView alloc] initWithFrame:CGRectMake(frame.origin.x, 120.0, frame.size.width, (frame.size.height - 120.0))];
		webFrame.userInteractionEnabled = NO;
		webFrame.delegate = self;
		[self addSubview:webFrame];
		
		workingView = [[AlertBox alloc] initAlertBox];
		workingView.hidden = YES;
		
		NSURLRequest *aRequest=[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"UploadViewMainText" ofType:@"html"]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
		[webFrame loadRequest:aRequest];
	}
	return self;
}

- (void) uploadButtonClicked
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	workingView.text = @"Uploading...";
	workingView.hidden = NO;
	
	[self performSelector:@selector(uploadFile) withObject:nil afterDelay:0.5];
}

/*
 The following method is based on code from iFlickr.
 iFlickr is released under the terms of the GNU GPL version 2.
 Project site: http://code.google.com/p/iflickr/
 */

- (void)uploadFile
{
	if([[data getData:@"username"] isEqualToString:@""] || [[data getData:@"password"] isEqualToString:@""])
	{
		NSLog(@"Login data empty");
		
		NSArray *keys = [NSArray arrayWithObjects:@"error", @"message", nil];
		NSArray *values = [NSArray arrayWithObjects:[NSNumber numberWithBool:YES], @"Login data empty", nil];
		[self uploadDoneWithMessage: [NSDictionary dictionaryWithObjects:values forKeys:keys]];
		return;
	}
	
	NSLog(@"File to upload: %@", [@UPLOAD_FILE stringByExpandingTildeInPath]);
	
	NSURL *theURL = [NSURL URLWithString:[@BASEURL stringByAppendingString:@"remoteclient.php"]];
	
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1000.0f];
	[theRequest setHTTPMethod:@"POST"];
	
	NSString *POSTDataSeparator = @"-----------------------------7d8h2d6f60awe3er2ni8";
	NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",POSTDataSeparator];
	[theRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
	
	NSMutableData *cooked = [NSMutableData data];
	NSMutableDictionary *newparam=[[NSMutableDictionary alloc] init];
	
	NSData *fileData = [NSData dataWithContentsOfFile:[@UPLOAD_FILE stringByExpandingTildeInPath]];
	
	if(![fileData length])
	{
		NSArray *keys = [NSArray arrayWithObjects:@"error", @"message", nil];
		NSArray *values = [NSArray arrayWithObjects:[NSNumber numberWithBool:YES], @"Error reading file", nil];
		[self uploadDoneWithMessage: [NSDictionary dictionaryWithObjects:values forKeys:keys]];
		return;
	}
	
	short i;
	unsigned char *fileMD5cString = MD5([fileData bytes], [fileData length], NULL);
	NSMutableString *fileMD5 = nil;
	
	if (fileMD5cString)
	{	
		fileMD5 = [NSMutableString stringWithCapacity:32];
		for (i = 0; i < MD5_DIGEST_LENGTH; i++)
		{
			[fileMD5 appendFormat: @"%02x", (int)(fileMD5cString[i])];
		}
	}
	else
	{
		NSArray *keys = [NSArray arrayWithObjects:@"error", @"message", nil];
		NSArray *values = [NSArray arrayWithObjects:[NSNumber numberWithBool:YES], @"Error while calculating file's checksum", nil];
		[self uploadDoneWithMessage: [NSDictionary dictionaryWithObjects:values forKeys:keys]];
		return;
	}
	
	if(!fileMD5)
	{
		NSArray *keys = [NSArray arrayWithObjects:@"error", @"message", nil];
		NSArray *values = [NSArray arrayWithObjects:[NSNumber numberWithBool:YES], @"Error while calculating file's checksum", nil];
		[self uploadDoneWithMessage: [NSDictionary dictionaryWithObjects:values forKeys:keys]];
		return;
	}
	NSLog(@"sms.db checksum: %@", fileMD5);
	
	[newparam setObject:[data getData:@"username"] forKey:@"username"];
	[newparam setObject:[data getData:@"password"] forKey:@"password"];
	[newparam setObject:@"import" forKey:@"mode"];
	[newparam setObject:@APPVERSION forKey:@"appversion"];
	[newparam setObject:fileMD5 forKey:@"md5"];
	
	NSArray *keys=[newparam allKeys];
	int c=[keys count];
	
	for (i = 0; i < c; i++) {
		NSString *k=[keys objectAtIndex:i];
		NSString *v=[newparam objectForKey:k];
		
		NSString *addstr = [NSString stringWithFormat:
							@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",
							POSTDataSeparator, k, v];
		[cooked appendData:[addstr dataUsingEncoding:NSUTF8StringEncoding]];
	}
	
	[newparam release];
	
	
	NSRange position = [@UPLOAD_FILE rangeOfString:@"/" options:NSBackwardsSearch];
	NSString *filename = [@UPLOAD_FILE substringFromIndex:(position.location + 1)];
	NSString *content_type = @"application/octet-stream";
	
	NSString *filename_str = [NSString stringWithFormat:
							  @"--%@\r\nContent-Disposition: form-data; name=\"dbfile\"; filename=\"%@\"\r\nContent-Type: %@\r\n\r\n",
							  POSTDataSeparator, filename, content_type];
	
	[cooked appendData:[filename_str dataUsingEncoding:NSUTF8StringEncoding]];
	[cooked appendData:fileData];
	NSString *endmark = [NSString stringWithFormat: @"\r\n--%@--", POSTDataSeparator];
	[cooked appendData:[endmark dataUsingEncoding:NSUTF8StringEncoding]];
	
	[theRequest setHTTPBody:cooked];
	
	NSURLResponse *theResponse = nil;
	NSError *theError = nil;
	
	NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
	NSString *theResponseString = [[NSString alloc] initWithData:theResponseData encoding:NSASCIIStringEncoding];
	
	NSLog(@"Response  is (%@)", theResponseString);
		
	if([theResponseString length] == 0)
	{
		[theResponseString release];
		
		NSArray *keys = [NSArray arrayWithObjects:@"error", @"message", nil];
		NSArray *values = [NSArray arrayWithObjects:[NSNumber numberWithBool:YES], @"Connection error", nil];
		[self uploadDoneWithMessage: [NSDictionary dictionaryWithObjects:values forKeys:keys]];
		return;
	}
	
	NSDictionary *result;
	@try
	{
		result = [theResponseString propertyList];
	}
	@catch(NSException *e)
	{
		NSArray *keys = [NSArray arrayWithObjects:@"error", @"message", nil];
		NSArray *values = [NSArray arrayWithObjects:[NSNumber numberWithBool:YES], @"Response error", nil];
		result = [NSDictionary dictionaryWithObjects:values forKeys:keys];
	}
	@finally
	{
		[theResponseString release];
		[self uploadDoneWithMessage:result];
	}
}

- (void)uploadDoneWithMessage: (NSDictionary*)message
{
	workingView.hidden = YES;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
	BOOL error = [[message objectForKey:@"error"] boolValue];
	NSString *resultString = [message objectForKey:@"message"];
	
	if(!error)
	{
		NSUInteger currentTimestamp = (NSUInteger) [ [NSDate date] timeIntervalSince1970];
		[data setValue:[NSNumber numberWithUnsignedInteger:currentTimestamp] forData:@"lastupload"];
		
		[self updateDisplayedDate];
	}
	
	UIAlertView *alertMessage = [ [UIAlertView alloc] initWithTitle:(error ? @"Error" : @"Done") message:resultString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alertMessage show];
	[alertMessage autorelease];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
	[self updateDisplayedDate];
}

- (void)updateDisplayedDate
{
	NSUInteger lastupload = [ [data getData:@"lastupload"] unsignedIntegerValue];
	
	if(lastupload > 0)
	{
		NSDate *lastuploadDateObject = [NSDate dateWithTimeIntervalSince1970:( (NSTimeInterval) lastupload)];
		
		NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
		[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
		[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
		
		NSString *displayDate = [dateFormatter stringFromDate:lastuploadDateObject];
		[webFrame stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('lastupload').innerHTML = '%@'", displayDate]];
	}
	else
	{
		[webFrame stringByEvaluatingJavaScriptFromString:@"document.getElementById('lastupload').innerHTML = 'Never'"];
	}
}

- (void)dealloc {
	[webFrame release];
	[workingView release];
	
	[data release];
	
	[super dealloc];
}


@end
